package api

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"hitme/go-api/logic/repository"
	"hitme/go-api/models"
	"net/http"
	"strings"
)

const (
	endpoint = "oss-cn-beijing.aliyuncs.com"
	accessKeyID = "LTAI4G1Qs6CrdUkyUeiDo3Bj"
	accessKeySecret = "A4w3F2S4dXmFfuby1wpKqDdLU99Shu"
	bucketName = "word-may"
	uploadFilePath = "uploads/"
	ossPrefix = "https://word-may.oss-cn-beijing.aliyuncs.com/"
)

type ossApi struct{}

var OssApi = new(ossApi)

// PutObjectRemoteUrl 上传远程文件
func (r *ossApi) PutObjectRemoteUrl(url string) (*OssPutObjectRemoteUrlResponse, error) {
	// 获取远程文件资源
	res, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	client, err := oss.New(endpoint, accessKeyID, accessKeySecret)

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return nil, err
	}

	urls := strings.Split(url, "/")
	objectKey := uploadFilePath + urls[len(urls) - 1]
	err = bucket.PutObject(objectKey, res.Body)
	if err != nil {
		return nil, err
	}

	// 保存文件信息
	repository.OssFileRep.Create(models.OssFile{
		EndPoint: endpoint,
		AccessKeyId: accessKeyID,
		AccessKeySecret: accessKeySecret,
		BucketName: bucketName,
		Object: objectKey,
		Url: url,
	})

	return &OssPutObjectRemoteUrlResponse{
		FileUrl: ossPrefix + objectKey,
		Object: objectKey,
	}, nil
}

// DeleteObject 删除oss文件
func (r *ossApi) DeleteObject(endPoint, accessKeyId, accessKeySecret, bucketName, object string) error {
	client, err := oss.New(endPoint, accessKeyId, accessKeySecret)
	if err != nil {
		return err
	}

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}

	err = bucket.DeleteObject(object)
	if err != nil {
		return err
	}

	return nil
}